package jwt

import (
	"errors"
	"time"

	"github.com/dgrijalva/jwt-go"
)

// IdentityClaims 用户的 JWT KEY
type IdentityClaims struct {
	AccountOpenID string `json:"account_openid"`
	AccountID     int    `json:"account_id"`
	AccountRole   string `json:"account_role"`
	SessionKey    string `json:"session_key"`
	jwt.StandardClaims
}

// 加密的密钥
var (
	JWTKey           = []byte("go-cdt-wdx")
	JWTTokenDuration = 300
	JWTIssuer        = "wdxtub"
)

// GenerateWebToken 生成 web 端 token
func GenerateWebToken(id int, role string) (string, error) {
	duration := int64(JWTTokenDuration)
	openID := "pcweb_root"
	sessionKey := "pcweb_root"
	claims := IdentityClaims{
		openID,
		id,
		role,
		sessionKey,
		jwt.StandardClaims{
			NotBefore: int64(time.Now().Unix()),
			IssuedAt:  int64(time.Now().Unix()),
			ExpiresAt: int64(time.Now().Unix() + duration),
			Issuer:    JWTIssuer,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(JWTKey)
}

// GenerateWeappToken 根据微信的返回生成对应的 token
func GenerateWeappToken(openID, sessionKey string, accountID int) (string, error) {
	duration := int64(JWTTokenDuration)
	claims := IdentityClaims{
		openID,
		accountID,
		"user",
		sessionKey,
		jwt.StandardClaims{
			NotBefore: int64(time.Now().Unix()),
			IssuedAt:  int64(time.Now().Unix()),
			ExpiresAt: int64(time.Now().Unix() + duration),
			Issuer:    JWTIssuer,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(JWTKey)
}

// ParseToken 验证是否是有效的 Token
func ParseToken(tokenString string) (*IdentityClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &IdentityClaims{}, func(token *jwt.Token) (interface{}, error) {
		return JWTKey, nil
	})

	if token == nil {
		return nil, errors.New("token 字段为空")
	}

	if claims, ok := token.Claims.(*IdentityClaims); ok && token.Valid {
		// 验证成功，返回信息
		return claims, err
	}

	// 验证失败
	return nil, errors.New("token 验证失败")
}
